#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import time
import tkinter as tk
from tkinter import messagebox
import threading

# 获取环境变量，如果不存在则使用默认值
RESOLVE_SCRIPT_API = os.environ.get('PROGRAMDATA', 'C:\\ProgramData') + r"\Blackmagic Design\DaVinci Resolve\Support\Developer\Scripting"
RESOLVE_SCRIPT_LIB = r"C:\Program Files\Blackmagic Design\DaVinci Resolve\fusionscript.dll"

# 更新 PYTHONPATH 环境变量
os.environ['PYTHONPATH'] = os.environ.get('PYTHONPATH', '') + ";" + RESOLVE_SCRIPT_API + "\\Modules\\"



# 添加DaVinci Resolve脚本API路径到sys.path
sys.path.append(RESOLVE_SCRIPT_API + "/Modules/")

# 现在可以安全地导入DaVinciResolveScript
import DaVinciResolveScript as dvr_script

# create_folders_in_project 和 create_projects 函数的逻辑保持原样
def create_folders_in_project(project, folder_names):
    media_pool = project.GetMediaPool()
    if not media_pool:
        print("无法获取媒体池")
        return False

    root_folder = media_pool.GetRootFolder()
    for folder_name in folder_names:
        folder_exists = False
        sub_folders = root_folder.GetSubFolders()
        if isinstance(sub_folders, list):
            for folder in sub_folders:
                if hasattr(folder, 'GetName') and folder.GetName() == folder_name:
                    folder_exists = True
                    break

        if not folder_exists:
            if not media_pool.AddSubFolder(root_folder, folder_name):
                print(f"无法创建文件夹: {folder_name}")
                return False
    return True

def create_projects(num_episodes):
    resolve = dvr_script.scriptapp("Resolve")
    projectManager = resolve.GetProjectManager()

    top_level_folders = ["DI", "IO", "test"]
    for folder in top_level_folders:
        projectManager.CreateFolder(folder)

    projectManager.OpenFolder("DI")
    di_subfolders = ["Feature", "Trailer"]
    for subfolder in di_subfolders:
        projectManager.CreateFolder(subfolder)
        time.sleep(1)

    projectManager.GotoRootFolder()
    time.sleep(1)

    if projectManager.OpenFolder("DI"):
        if projectManager.OpenFolder("Feature"):
            for i in range(1, num_episodes + 1):
                project_name = f"EP{i:02d}"
                new_project = projectManager.CreateProject(project_name)
                if new_project:
                    folder_names = ["SOURCE", "Timelines", "WP", "FROM_VFX", "FLIPCARD", "PTPW", "SOUND", "SUB", "QC"]
                    if not create_folders_in_project(new_project, folder_names):
                        print(f"无法在工程 {project_name} 中创建文件夹层级")
                else:
                    print(f"无法创建工程: {project_name}")
                time.sleep(1)

    projectManager.GotoRootFolder()
    time.sleep(1)

    if projectManager.OpenFolder("IO"):
        io_project_names = ["IO_01", "IO_02", "IO_03"]
        io_folder_names = ["SOURCE", "TO_VFX", "QC", "FEATURE"]

        for project_name in io_project_names:
            new_project = projectManager.CreateProject(project_name)
            if new_project:
                if not create_folders_in_project(new_project, io_folder_names):
                    print(f"无法在工程 {project_name} 中创建文件夹层级")
                projectManager.SaveProject()
                projectManager.CloseProject()
            else:
                print(f"无法创建工程: {project_name}")

    messagebox.showinfo("完成", "工程文件夹和工程创建完成。")

# 使用 Tkinter 重写 GUI 部分
class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title('新剧集项目入库插件')
        self.initUI()

    def initUI(self):
        label = tk.Label(self, text='请输入新来的剧集项目共有多少集（纯数字）:')
        label.pack()

        self.textbox = tk.Entry(self)
        self.textbox.pack()

        button = tk.Button(self, text='开始创建', command=self.on_click)
        button.pack()

    def on_click(self):
        num_episodes = self.textbox.get()
        try:
            num_episodes = int(num_episodes)
            # 创建并启动一个新线程来运行 create_projects 函数
            thread = threading.Thread(target=create_projects, args=(num_episodes,))
            thread.start()
            messagebox.showinfo("正在运行", "正在运行中，请稍后。")
        except ValueError:
            messagebox.showwarning("错误", "请输入有效的数字。")

def main():
    app = App()
    app.mainloop()

if __name__ == '__main__':
    main()
